package com.tuyenmonkey.mkloader;

import com.tuyenmonkey.mkloader.callback.InvalidateListener;
import com.tuyenmonkey.mkloader.type.LoaderView;
import com.tuyenmonkey.mkloader.util.LoaderGenerator;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.app.Context;

/**
 * Created by Tuyen Nguyen on 2/5/17.
 */

public class MKLoader extends Component implements Component.BindStateChangedListener,InvalidateListener,
        Component.DrawTask {
  private LoaderView loaderView;

  public MKLoader(Context context, AttrSet attrs) {
    super(context, attrs);
    initialize(context, attrs, 0);
  }

  public MKLoader(Context context, AttrSet attrs, String defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  private void initialize(Context context, AttrSet attrs, int defStyleAttr) {
    int loaderType = attrs.getAttr("mk_type").get().getIntegerValue();
    loaderView = LoaderGenerator.generateLoaderView(context,loaderType);
    loaderView.setSize();
    loaderView.initializeObjects();
    this.setBindStateChangedListener(this);
    invalidate();
  }
  @Override
  public void invalidate() {
    addDrawTask(this::onDraw);
  }

  @Override
  public void onDraw(Component component, Canvas canvas) {
    this.loaderView.draw(canvas);
  }

  @Override
  public void onComponentBoundToWindow(Component component) {
     loaderView.setInvalidateListener(this);
      loaderView.setUpAnimation();
  }

  @Override
  public void onComponentUnboundFromWindow(Component component) {
    loaderView.onDetach();
  }

  @Override
  public void reDraw() {
    invalidate();
  }
}



